package edu.ncsu.csc.ip.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Timer;

import edu.ncsu.csc.ip.common.Log;
import edu.ncsu.csc.ip.server.timer.TTLUpdateTask;

/**
 * Class <code>RegistrationServer</code>
 * 
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class RegistrationServer {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = null;
		boolean isListening = true;

		// Schedule a timer in a background thread to update TTLs in client index
				Timer timer = new Timer();
				timer.scheduleAtFixedRate(new TTLUpdateTask(), 1000, ClientIndex.TTL_UPDATE_INTERVAL*1000);

		int defaultPort = 65423;
		int port = defaultPort;
		try {
			port = Integer.parseInt(args[0]);
		} catch (NumberFormatException nfe) {
			Log.println("Port is not a number: " + args[0]
					+ ". Using the default port:" + port);
		} catch (ArrayIndexOutOfBoundsException aie) {
			Log.println("No port specified. Using the default port:"
					+ port);
		}

		try {
			serverSocket = new ServerSocket(port);
			Log.println("Server is listening on port: " + port + " . . . ");
		} catch (IOException e) {
			Log.err("Could not listen on port: " + port + ". Closing program ...");
			System.exit(-1);
		}

		while (isListening) {
			// Listens for a connection to be made to this socket and accepts
			// it. The method blocks until a connection is made.
			new RegistrationServerThread(serverSocket.accept()).start();
		}

		serverSocket.close();
	}
}
